package com.hjw.smsapp;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.hjw.smsapp.base.BaseActivity;
import com.hjw.smsapp.service.SmsObserverService;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LoginActivity extends BaseActivity {
    private EditText etUser, etPsw, etIp;
    private LinearLayout llIp;
    private boolean isIPSet = false, autoLogin = true;
    private SharedPreferences sharedPreferences;
    private String ip, user, psw;
    private boolean isFirst = true;

    @Override
    public int getContentViewId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        etUser = findViewById(R.id.et_user);
        etPsw = findViewById(R.id.et_psw);
        etIp = findViewById(R.id.et_ip);
        llIp = findViewById(R.id.ll_ip);
        findViewById(R.id.ll_content).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeKeyboard();
            }
        });
    }

    @Override
    public void initData() {
        SmsApplication.removeActivityExist(this);
        if (getIntent() != null) {
            isIPSet = getIntent().getBooleanExtra("setIp", false);
            autoLogin = getIntent().getBooleanExtra("autoLogin", true);
        }

        sharedPreferences = getSharedPreferences("data", Context.MODE_PRIVATE);
        ip = sharedPreferences.getString("ip", "http://www.hjwkj.top/api/login.php");
        user = sharedPreferences.getString("username", "");
        psw = sharedPreferences.getString("password", "");
        isFirst = sharedPreferences.getBoolean("first", true);
        etIp.setText(ip);
        etUser.setText(user);
        etPsw.setText(psw);
        if (TextUtils.isEmpty(ip) || isIPSet || isFirst) {
            llIp.setVisibility(View.VISIBLE);
            autoLogin = false;
        } else {
            llIp.setVisibility(View.GONE);
        }

        if (autoLogin) {
            if (isServiceExisted(SmsObserverService.class.getName())) {
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                finish();
            } else {
                onLogin(null);
            }
        }
    }

    public void onLogin(View view) {
        user = etUser.getText().toString();
        psw = etPsw.getText().toString();
        ip = etIp.getText().toString();
        if (!TextUtils.isEmpty(user) && !TextUtils.isEmpty(psw) && !TextUtils.isEmpty(psw)) {
            login(user, psw, ip);
        } else {
            Toast.makeText(this, "请输入账号和密码", Toast.LENGTH_SHORT).show();
        }
    }

    public void onExit(View view) {
        Intent intent = new Intent(this, SmsObserverService.class);
        stopService(intent);
        SmsApplication.exit();
    }

    private void login(final String username, final String password, final String ip) {
        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
        formBody.add("username", username);//传递键值对参数
        formBody.add("password", password);//传递键值对参数
        final Request request = new Request.Builder()//创建Request 对象。
                .url(ip)
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                showToast("登录失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response != null && response.isSuccessful()) {//回调的方法执行在子线程。
                    try {
                        JSONObject result = new JSONObject(response.body().string());
                        System.out.println(result.toString(2));
                        //{"code":10001,"data":null,"msg":false}
                        int code = result.optInt("code");
                        String msg = result.optString("msg");
                        if (code == 10000) {
                            loginSuccess(username, password, ip);
                            //成功
                            return;
                        } else {
                            //失败
                            showToast(msg);
                            return;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                showToast("登录失败");
            }
        });
    }

    private void loginSuccess(String username, String password, String ip) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        String smsIp = sharedPreferences.getString("smsIp", "http://www.hjwkj.top/api/post_message.php");
        editor.putString("username", username);
        editor.putString("password", password);
        editor.putString("ip", ip);
        editor.putString("smsIp", smsIp);
        editor.putBoolean("first", false);
        editor.apply();
        startActivity(new Intent(LoginActivity.this, MainActivity.class));
        finish();
    }
}
